package com.example.test_load_pic_rough.adapter;

import static com.xuexiang.xui.utils.ResUtils.getResources;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.test_load_pic_rough.R;
import com.example.test_load_pic_rough.bean.User;
import com.xuexiang.xui.adapter.recyclerview.RecyclerViewHolder;

import java.util.ArrayList;

public class ViewListAdapter extends RecyclerView.Adapter<ViewListAdapter.ViewListItemHolder> {

    ArrayList<User> mList ;

    public int rows = 2;   //宫格显示的时候的 行数和列数
    public int columns = 3 ;

    public ViewListAdapter(ArrayList<User> mList) {
        this.mList = mList;
    }

    public ArrayList<User> getmList() {
        return mList;
    }

    public void setmList(ArrayList<User> mList) {
        this.mList = mList;
    }

    @NonNull
    @Override
    public ViewListItemHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View inflate = LayoutInflater.from(parent.getContext()).inflate(R.layout.view_list_item, parent, false);
        //这里不要直接给到holder ，改变一下view的大小
        ViewGroup.LayoutParams layoutParams = inflate.getLayoutParams();
        //分割为若干个小的块
        int dividLine = (int)getResources().getDimension(R.dimen.common_decorate); //空出来分割线的宽度
        if (parent.getHeight() != 0 && parent.getWidth() != 0){  //有问题 这里的长宽都是-1 不对
          layoutParams.width = (parent.getWidth() - columns*dividLine*2) / columns ; //*2是因为左右两边
          layoutParams.height  = (parent.getHeight() - rows*dividLine*2) / rows;  //*2 是因为上下两边
          inflate.setLayoutParams(layoutParams);
        }
        return new ViewListItemHolder(inflate);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewListItemHolder holder, int position) {
        User user = mList.get(position);
        holder.tvUserName.setText(user.getName());
        holder.tvUserNumber.setText(user.getNumber());
        ((View)holder.tvUserNumber.getParent()).setOnClickListener(
                view -> Toast.makeText(holder.getContext(),"你点击了第【"+position+"】个",Toast.LENGTH_SHORT).show());
    }

    @Override
    public int getItemCount() {
        return mList == null ? 0 : mList.size();
    }

    class ViewListItemHolder extends RecyclerViewHolder {
        private TextView tvUserName ;
        private TextView tvUserNumber ;

        public ViewListItemHolder(View itemView) {
            super(itemView);
            tvUserName = itemView.findViewById(R.id.user_name);
            tvUserNumber = itemView.findViewById(R.id.user_number);
        }
    }
}
